package com.boot.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@ComponentScan(basePackages = {"com.boot"})
public class MapperJavaConfig {
    //把sqlSessionFactory加入ioc容器,用配置的方式可以解决xml效率低的问题
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //datasource独立出去配置是为了解决加载顺序问题
        sqlSessionFactoryBean.setDataSource(dataSource);
        //MyBatis的配置类
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //配置驼峰名字
        configuration.setMapUnderscoreToCamelCase(true);
        //配置日志
        configuration.setLogImpl(Slf4jImpl.class);
        //自动映射别名
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        //配置到sqlSessionFactoryBean中
        sqlSessionFactoryBean.setConfiguration(configuration);

        //别名覆盖范围设置
        sqlSessionFactoryBean.setTypeAliasesPackage("com.boot.pojo");

        //配置分页插件
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(properties);

        //加载分页插件
        sqlSessionFactoryBean.addPlugins(pageInterceptor);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.boot.mapper");
        return mapperScannerConfigurer;
    }
}
